package cn.icyzx.controller;

import cn.icyzx.models.User;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;

import org.springframework.validation.Errors;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.*;
import cn.icyzx.service.LoginService;
import cn.icyzx.util.StaticConstUtil;


import javax.servlet.http.HttpSession;
import javax.validation.Valid;

import static cn.icyzx.util.StaticConstUtil.*;

/**
 * Created by 郑凯 on 2016/8/19.
 */
@Controller
public class LoginProcess {

    private static Logger logger = Logger.getLogger(LoginProcess.class);

    /**
     * loginService contains login ,register ,
     */
    @Autowired
    public LoginService loginService;

    /**
     * login
     *
     * @param session 需要处理有关session的有关处理
     * @return java.lang.String 返回字符串来同步消息
     */
    @RequestMapping(value = "/login", method = RequestMethod.POST, produces = "text/html;charset=utf-8")
    @ResponseBody
    String login(@RequestParam("usernameOrEmail") String usernameOrEmail, @RequestParam("password") String password, HttpSession session) {
        String tip = loginService.login(usernameOrEmail, password, session);

        if (LOGIN_SUCCESS.equals(tip))
            return LOGIN_SUCCESS;
        else return tip;
    }

    /**
     * register 注册页面
     *
     * @param model
     * @return java.lang.String 返回页面
     */
    @RequestMapping(value = "/register", method = RequestMethod.GET)
    public String register(Model model) {
        model.addAttribute("server", StaticConstUtil.SERVER_NAME);
        return "register";
    }

    /**
     * register
     *
     * @param user   需要校验并封装好的User
     * @param errors JSR303校验结果
     * @return java.lang.String 返回注册进度信息
     */
    @RequestMapping(value = "/register", method = RequestMethod.POST, produces = "text/html;charset=utf-8")
    @ResponseBody
    public String register(@ModelAttribute @Valid User user, Errors errors) {

        if (errors.hasErrors()) {
            for (ObjectError error : errors.getAllErrors()) {
                return error.getDefaultMessage();  //为了体现出很好的提示，只返回一个error
            }
        } else {
            String Tip = check(user.getEmail(), user.getUsername()); //更好的应该加校验器的，不过我想无xml的配置，所以没有用（改进条件：不建议用spring）
            if (!Tip.equals(""))
                return Tip;
        }

        final String Tip = loginService.register(user);
        return Tip;

    }


    /**
     * check 注册时check部分
     *
     * @param username 要check的用户名
     * @param email    要check的Email
     * @return java.lang.String 返回提示信息
     */
    @RequestMapping(value = "/check", method = RequestMethod.GET, produces = "text/html;charset=utf-8")
    private @ResponseBody
    String check(@RequestParam("username") String username, @RequestParam("email") String email) {

        try {
            if (!username.equals("") && loginService.checkName(username))
                return USERNAME_DISABLE;

            if (!email.equals("") && loginService.checkEmail(email))
                return EMAIL_DISABLE;

        } catch (Exception e) {
            logger.error("校验错误：" + e.getMessage());
            return INPUT_DISABLE;
        }
        return "";
    }


}
